package com.billjc.activity.exception;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.billjc.activity.Result.CodeMsg;
import com.billjc.activity.Result.Result;

@ControllerAdvice
public class GlobalExceptionHandler {
	public static final String DEFAULT_ERROR_VIEW = "error";

	/**
	 * 全局异常处理--->页面
	 * 
	 * @param req
	 * @param e
	 * @return
	 * @throws Exception
	 */
	/*@ExceptionHandler(value = Exception.class)
	public ModelAndView pageErrorHandler(HttpServletRequest req, Exception e) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.addObject("exception", e);
		mav.addObject("url", req.getRequestURL());
		mav.setViewName(DEFAULT_ERROR_VIEW);
		return mav;
	}*/

	/**
	 * 全局异常处理----->json
	 * 
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
    public Result<String> exceptionHandler(HttpServletRequest request, Exception e){
       if(e instanceof GlobalException){
           GlobalException ex = (GlobalException) e;
           return Result.error(ex.getCodeMsg());
       }else if(e instanceof BindException){
           BindException ex = (BindException) e;
           List<ObjectError> errors = ex.getAllErrors();
           ObjectError error = errors.get(0);
           String msg = error.getDefaultMessage();
           return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
       }else if (e instanceof MissingPathVariableException) {
		   MissingPathVariableException ex = (MissingPathVariableException) e;
		   String errorMsg = ex.getMessage();
		   return Result.error(CodeMsg.BIND_ERROR.fillArgs(errorMsg));
	}else{
           return Result.error(CodeMsg.SERVER_ERROR);
       }
    }

}
